import axios from 'axios'
import Vue from 'vue'
import {app} from '@/main.js'

axios.defaults.timeout=30000
//
// axios.interceptors.request.use(function (config) {    // 这里的config包含每次请求的内容
//   let token = getToken()
//   if (token) {
//     config.headers.Authorization = 'JWT '+ `${token}`;
//   }else {
//     window.location.pathname = '/login'
//   }
//   return config;
// }, function (err) {
//   return Promise.reject(err);
// })
//拦截器
// axios.interceptors.response.use(
//   response => {
//     return response
//   },
//   error => {
//     if (error.response) {
//       switch (error.response.status) {
//         case 401:
//           // 返回 401 清除token信息并跳转到登录页面
//           console.log('-骨过期')
//           console.log(this)
//
//
//           // confirm('过期')
//           // router.replace({
//           //   path: '/login'
//           // })
//           // location.reload()
//       }
//     }
//     return Promise.reject(error)   // 返回接口返回的错误信息
//   })

import language from "../lang/utils";

let requestLang = ''
if (language === 'zh') {
  requestLang = 'zh_CN'
}
if (language === 'en') {
  requestLang = 'en_US'
}

//请求的封装
const myGet = (url, data, code200, error, lastdo) => {
  if(requestLang&&data){
    if(data.params){
      data.params.lang = requestLang
    }else{
      data.params = {lang:requestLang}
    }

  }

  axios.get(url, data).then(res => {
    if (res.data.code === 200 || url==='./api/program/download') {
      code200(res)
    } else {
      if (error) {
        error(res)
      } else {
        // showErrorToast('数据返回出错：'+ res.data.msg)
        console.log('请求出错：msg:' + res.data.msg + '---' + url)
      }
    }
  }).catch(err => {
    // console.log(err.response.status)

    if (err&&err.response&&err.response.status === 401) {
      //需要重新登录
      // console.log('ss-----------------------')
      // console.log(Vue)
      // Vue.$wlsUtil.linkToPath('/login')
      return
    } else {
      // console.log('-----------------------')
      // console.log(this)
      // this.linkToPath('/login')
    }

    if (error) {
      error(err)
    } else {
      showErrorToast('error 请求失败')
      console.log(err)
    }
  }).finally(() => {

    if (lastdo) {
      lastdo()
    }
    // console.log('---------finalu')
  })
}


const myPost = function (url, data, code200, error) {
  // axios.defaults.headers.post['Content-Type'] = 'application/form-data';

  // console.log('-sdds-d-sd-sd-s-d-ds')
  axios.post(url, data).then(res => {
    console.log(res)
    if (res.data.code === 200) {
      code200(res)
    } else {
      if (error) {
        error(res)
      } else {
        showErrorToast(res.data.message)
        // showErrorToast('error 数据返回出错：' + res.data.msg)
        console.log('请求出错：msg:' + res.data.msg + '---' + url)
      }
    }
  }).catch(err => {
    if (error) {
      error(err)
    } else {
      showErrorToast('error 请求失败')
      console.log(err)
    }
  })
}

const myPostParams = function (url, params, code200, error) {
  // axios.defaults.headers.post['Content-Type'] = 'application/form-data';

  // console.log('-sdds-d-sd-sd-s-d-ds')
  axios({
    method:'post',
    url, params
  }).then(res => {
    console.log(res)
    if (res.data.code === 200) {
      code200(res)
    } else {
      if (error) {
        error(res)
      } else {
        showErrorToast('error 数据返回出错：' + res.data.msg)
        console.log('请求出错：msg:' + res.data.msg + '---' + url)
      }
    }
  }).catch(err => {
    if (error) {
      error(err)
    } else {
      showErrorToast('error 请求失败')
      console.log(err)
    }
  })
}


const showSuccessToast = function (msg) {
  app.$message({
    message: msg,
    type: 'success'
  })
}


const showErrorToast = function (msg) {
  app.$message.error(msg)
}


const linkToPath = function (path) {
  app.$router.push({path: path})
}

const goPageBack = function (context) {
  app.$router.back(-1)
}

const deepCopy = function (obj) {
  if (typeof obj != 'object') {
    return obj;
  }
  var newobj = {};
  for (var attr in obj) {
    newobj[attr] = deepCopy(obj[attr]);
  }
  return newobj;
}

const downLoadFile = function (path) {

  try {
    var elemIF = document.createElement("iframe");
    elemIF.src = path;
    elemIF.style.display = "none";
    document.body.appendChild(elemIF);
  } catch (e) {
  }
}

const myPostExcel = (url, params, onProgress,method) => {
  let _method=method?method:"post"
  return new Promise((resolve, reject) => {
    axios[_method](
      url,
      params,
      {
        headers: {
          'Content-Type': 'application/json;application/octet-stream;charset=utf-8'
        },
        'responseType': 'arraybuffer',
        onProgress
      }
    ).then((res, c) => {
      try {
        let enc = new TextDecoder('utf-8')
        let json = JSON.parse(enc.decode(new Uint8Array(res.data)))
        resolve(json)
      } catch (e) {
        let b = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        const  defaultFilename = new Date().getTime() + '.xls'
        const RegEx = /filename=([^;]*)(;|$)/;
        const filenameRes = RegEx.exec(res.headers['content-disposition']) || [];
        const resFilename = decodeURIComponent(filenameRes[1]) || ''
        const filename = resFilename || defaultFilename
        console.log(filename, '文件名')
        url = URL.createObjectURL(b)
        let link = document.createElement('a')
        link.download = filename
        link.href = url
        link.click()
        resolve({
          data: {
            code:200
          }
        })
      }
    }).catch(err => {
      console.error(err)
      reject(err)
    })
  })
}

export default {
  myGet,
  myPost,
  myPostParams,
  myPostExcel,
  showSuccessToast,
  showErrorToast,
  linkToPath,
  goPageBack,
  deepCopy,
  downLoadFile
}
